package org.mii.safeguard_v1.base.jdbc;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

@Repository("baseJdbcDao")
public class BaseJdbcDaoImpl implements BaseJdbcDao  {
	@Autowired
	SimpleJdbcTemplate simpleJdbcTemplate;

	public <T> java.util.List<T> query(String sql, Class<T> clazz, T obj) {
		Assert.notNull(sql);
		Assert.notNull(obj);

		SqlParameterSource sps = new BeanPropertySqlParameterSource(obj);
		return simpleJdbcTemplate.query(sql, ParameterizedBeanPropertyRowMapper
				.newInstance(clazz), sps);
	}
	
	public <T> int update(String sql, T obj) {
		Assert.notNull(sql);
		Assert.notNull(obj);

		SqlParameterSource sps = new BeanPropertySqlParameterSource(obj);
		return simpleJdbcTemplate.update(sql, sps);
	}

	public <T> int[] batchUpdate(String sql, List<T> objs) {

		SqlParameterSource[] batchArgs = new SqlParameterSource[objs.size()];
		for (int i = 0; i < objs.size(); i++) {
			batchArgs[i] = new BeanPropertySqlParameterSource(objs.get(i));
		}

		return simpleJdbcTemplate.batchUpdate(sql, batchArgs);
	}
	
	public <T> T queryUnique(String sql, Class<T> clazz, T obj)
			throws JdbcDaoException {
		List<T> qr = query(sql, clazz, obj);
		if (qr == null)
			return null;
		if (qr.size() == 1)
			return qr.get(0);
		else {
			throw new JdbcDaoException("查询结果不唯一！");
		}

	}
}
